<template>
  <div class="project-purchase-detail">
    <van-form ref="form" @submit="formSubmited">
      <van-field
        v-model="form.serialNum"
        name="serialNum"
        label="编号"
        placeholder="保存后自动生成编号"
        disabled
        v-show="pageType == 1"
      />

      <van-field
        name="reportPeople"
        label="报备来源"
        required
        :rules="[{ required:true, message:'请选择报备来源', trigger:'onChange' }]"
      >
        <template #input>
          <van-radio-group v-model="form.reportPeople" direction="horizontal" :disabled="!canEdit">
            <van-radio
              :name="item.value"
              v-for="item in purchaseReportPeopleDict"
              :key="item.value"
            >{{ item.text }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        v-model="showForm.cusFullName_show"
        name="cusFullName"
        label="地产名称"
        placeholder="请选择地产名称"
        required
        readonly
        clickable
        :rules="[{ validator: cusAddDocsValidate, message: '请输入正确内容' }]"
        :disabled="!canEdit"
        @click="openFuzzyPopup('cusFullName', 'cusFullName', true)"
      />
      <van-popup v-model="popupVisible" position="top" @opened="fuzzyPopupOpened">
        <div class="salesmanPopupContainer">
          <van-search
            ref="popupDom"
            v-model="searchValue"
            placeholder="请输入搜索关键词"
            :show-action="showSearchAdd"
            @input="fuzzyInput"
            @clear="fuzzyClear"
          >
            <template #action>
              <div @click="fuzzyAdd" style="color:#1989fa">添加</div>
            </template>
          </van-search>
          <div class="salesmanItemContainer">
            <div
              v-for="item in searchArray"
              :key="'' + item.id + Math.random()"
              @click="fuzzyItemClick(item)"
              class="salesmanItem van-hairline--bottom"
            >{{ item[popupCtr.showKey] }}</div>
          </div>
        </div>
      </van-popup>

      <van-field
        v-model="form.projectName"
        name="projectName"
        label="集采名称"
        placeholder="请输入集采名称"
        required
        :disabled="!canEdit"
      />

      <van-field
        v-model="form.mainPerson"
        name="mainPerson"
        label="甲方负责人"
        placeholder="请输入甲方负责人"
        required
        :rules="[{ required:true, message:'请输入甲方负责人' }]"
        :disabled="!canEdit"
      />

      <van-field
        v-model="form.mainPerPhone"
        name="mainPerPhone"
        required
        label="直线/手机"
        placeholder="请输入直线/手机"
        :rules="[ { validator: (val)=>{ return val ? (/^1[3456789]\d{9}$/.test(val) || /^$|(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/.test(val)) : false }, message:'请输入正确的手机号' } ]"
        :disabled="!canEdit"
      />

      <van-field
        v-model="form.position"
        :disabled="!canEdit"
        name="position"
        required
        label="职位"
        :rules="[{ required:true, message:'请输入职位' }]"
        placeholder="请输入职位"
      />

      <van-field
        v-model="form.engineerAgent"
        name="engineerAgent"
        label="代理商"
        placeholder="请输入代理商"
        :disabled="!canEdit"
      />

      <van-field
        v-model="showForm.salesmanId_show"
        name="salesmanId"
        label="跟进业务员"
        placeholder="请选择跟进业务员"
        required
        readonly
        clickable
        :rules="[{ validator:salesmanValidate, message: '请输入正确内容' }]"
        :disabled="!canEdit"
        @click="openFuzzyPopup('salesmanId','nickName')"
      />

      <van-field
        readonly
        clickable
        name="tenderDate"
        :value="form.tenderDate"
        label="招标时间"
        placeholder="点击选择日期"
        required
        :disabled="!canEdit"
        @click="canEdit ? tenderDateShow = true : false"
      />
      <van-calendar
        ref="calendar"
        v-model="tenderDateShow"
        :default-date="tenderDateDefaultDate"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="tenderDateConfirm"
      />

      <van-field
        name="tenderRequest"
        label="招标要求"
        required
        :rules="[{ required:true, message:'请选择招标要求', trigger:'onChange' }]"
      >
        <template #input>
          <van-radio-group v-model="form.tenderRequest" direction="horizontal" :disabled="!canEdit">
            <van-radio
              :name="item.value"
              v-for="item in tenderRequestDict"
              :key="item.value"
            >{{ item.text }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        v-model="form.brandQuantity"
        name="brandQuantity"
        label="品牌数量"
        placeholder="请输入品牌数量"
        readonly
        type="number"
        clickable
        @click="canEdit ? brandQuantityShow = true : false"
      />
      <van-number-keyboard
        v-model="form.brandQuantity"
        close-button-text="完成"
        :show="brandQuantityShow"
        @blur="canEdit ? brandQuantityShow = false : false"
      />

      <van-field
        name="groupType"
        label="集采类型"
        required
        :rules="[{ required:true, message:'请选择集采类型', trigger:'onChange' }]"
      >
        <template #input>
          <van-radio-group v-model="form.groupType" direction="horizontal" :disabled="!canEdit">
            <van-radio
              :name="item.value"
              v-for="item in groupTypeDict"
              :key="item.value"
            >{{ item.text }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        v-model="form.groupAreaDesc"
        name="groupAreaDesc"
        label="区域集采说明"
        type="textarea"
        placeholder="请输入区域集采说明"
        :required="form.groupType == 1"
        :rules="[{ validator: groupAreaVali, message: '请输入区域集采说明' }]"
        :disabled="!canEdit"
      />

      <van-field
        v-model="form.detailFollowUp"
        name="detailFollowUp"
        label="详细跟进情况"
        type="textarea"
        placeholder="请输入详细跟进情况"
        :required="true"
        :rules="[{ required:true, message: '请输入详细跟进情况' }]"
        :disabled="!canEdit"
      />

      <van-field
        v-model="form.approveOpinion"
        name="approveOpinion"
        label="审批意见"
        type="textarea"
        autosize
        :disabled="true"
      />
    </van-form>
    <div style="margin: .3rem;" v-if="recordCanEdit">
      <van-row type="flex">
        <van-col class="bottomBtnCol" v-if="pageType == 1">
          <van-button
            round
            block
            type="default"
            native-type="button"
            @click="canEditBtnClick"
          >{{ canEdit?'取消':'编辑' }}</van-button>
        </van-col>
        <van-col class="bottomBtnCol">
          <van-button
            round
            block
            type="info"
            native-type="button"
            :disabled="!canEdit"
            @click="okBtnClick"
          >确定</van-button>
        </van-col>
      </van-row>
    </div>
  </div>
</template>

<script>
import Card from "@/components/Card";
import {
  _purchaseReportPeopleDict,
  _tenderRequestDict,
  _groupTypeDict
} from "@/utils/dict";
import { mapActions, mapMutations } from "vuex";
import {
  Skeleton,
  Form,
  Field,
  Picker,
  Calendar,
  RadioGroup,
  Radio,
  Popup,
  Button,
  Search,
  NumberKeyboard,
  Toast,
  Row,
  Col
} from "vant";
import Fuse from "fuse.js";
import { formatDate } from "@/utils";
export default {
  components: {
    Card,
    [Skeleton.name]: Skeleton,
    [Form.name]: Form,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [Calendar.name]: Calendar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Search.name]: Search,
    [NumberKeyboard.name]: NumberKeyboard,
    [Row.name]: Row,
    [Col.name]: Col
  },
  data() {
    return {
      title: "",
      pageType: 0,
      loading: true,
      form: {
        reportPeople: "",
        cusFullName: "",
        projectName: "",
        mainPerson: "",
        mainPerPhone: "",
        position: "",
        engineerAgent: "",
        salesmanId: "",
        tenderDate: "",
        tenderRequest: "",
        brandQuantity: "",
        groupType: "",
        groupAreaDesc: "",
        approveOpinion: "",
        detailFollowUp:""
      },

      tenderDateShow: false,
      brandQuantityShow: false,
      // 表单项展示用数据
      showForm: {
        cusFullName_show: "",
        salesmanId_show: ""
      },
      // 模糊搜索用弹窗控制
      popupCtr: {
        formName: "",
        showKey: ""
      },
      searchValue: "",
      popupVisible: false,
      searchArray: [],
      showSearchAdd: false,

      purchaseReportPeopleDict: _purchaseReportPeopleDict,
      tenderRequestDict: _tenderRequestDict,
      groupTypeDict: _groupTypeDict,

      salesmanIdArrOrigin: [],
      cusFullNameArrOrigin: [],

      tenderDateDefaultDate: new Date(),

      minDate: new Date("2000/01/01"),
      maxDate: new Date("2100/01/01"),

      canEdit: false,
      recordCanEdit: true // 作废或者审批拒绝则不能编辑
    };
  },
  watch: {
    "form.groupType"(val) {
      if (val == "2") {
        this.$refs.form.resetValidation("groupAreaDesc");
      }
    }
  },
  created() {
    if (this.$route.query.type == "add") {
      this.pageType = 0;
      this.canEdit = true;
    } else {
      this.pageType = 1;
    }
  },
  mounted() {
    this.loading = true;
    this.initData();
  },
  beforeDestroy() {
    this.resetDocsDetail();
  },
  methods: {
    ...mapActions({
      getCusDocsList: "projectPurchase/getCusDocsList",
      querySalesman: "cusAddDocs/querySalesman",
      getCusDocs: "projectPurchase/getCusDocs",
      addProjectPurchase: "projectPurchase/addProjectPurchase",
      updateProjectPurchase: "projectPurchase/updateProjectPurchase"
    }),
    ...mapMutations({
      resetDocsDetail: "projectPurchase/resetDocsDetail"
    }),
    initData() {
      let detail = this.$store.state.projectPurchase.projectPurchaseDetail;
      if (this.pageType == 1 && (detail.delFlag || detail.approveStatus == 0)) {
        this.recordCanEdit = false;
      }
      if (this.pageType == 1) {
        for (const key in detail) {
          if (detail.hasOwnProperty(key)) {
            const element = detail[key];
            this.form[key] = "" + element;
          }
        }
      }

      Promise.all([this.getCusDocs(), this.querySalesman()])
        .then(res => {
          console.log(res);
          let salesmanArr = res[1].data;
          let cusArr = res[0].data;
          if (salesmanArr.length) {
            this.salesmanIdArrOrigin = JSON.parse(JSON.stringify(salesmanArr));
            if (this.pageType == 1) {
              for (let i = 0, len = salesmanArr.length; i < len; i++) {
                if (salesmanArr[i].id == detail.salesmanId) {
                  this.showForm.salesmanId_show = salesmanArr[i].nickName;
                  break;
                }
              }
            }
          }

          if (cusArr.length) {
            this.cusFullNameArrOrigin = JSON.parse(JSON.stringify(cusArr));
            if (this.pageType == 1) {
              this.showForm.cusFullName_show = detail.cusFullName;
              this.form.cusFullName = detail.groupCusAddDocumentId;
              for (let i = 0, len = cusArr.length; i < len; i++) {
                if (cusArr[i].id == detail.cusFullName) {
                  this.showForm.cusFullName_show = cusArr[i].cusFullName;
                  break;
                }
              }
            }
          }
          this.loading = false;
          if (this.pageType == 1 && detail.tenderDate) {
            this.$nextTick(() => {
              let date = new Date(detail.tenderDate);
              this.tenderDateDefaultDate = date;
              this.$refs.calendar.reset();

              this.form.tenderDate = formatDate(date, "yyyy-MM-dd");
            });
          }
        })
        .catch(err => {
          console.log(err);
          this.loading = false;
        });
    },
    salesmanValidate(val) {
      return this.form.salesmanId ? true : false;
    },
    cusAddDocsValidate(val) {
      return this.form.cusFullName ? true : false;
    },
    groupAreaVali(val) {
      return this.form.groupType == "1" ? (val ? true : false) : true;
    },
    openFuzzyPopup(formName, showKey, showSearchAdd) {
      if (this.canEdit) {
        this.popupCtr.formName = formName;
        this.popupCtr.showKey = showKey;
        this.searchValue = "";
        this.searchArray = [];
        this.showSearchAdd = showSearchAdd;
        this.popupVisible = true;
      }
    },
    fuzzyPopupOpened() {
      let child = this.$refs.popupDom.getElementsByTagName("input");
      child[0].focus();
    },
    fuzzyItemClick(item) {//模糊搜索选项点击
      console.log(item);
      this.form[this.popupCtr.formName] = item.id;
      this.showForm[`${this.popupCtr.formName}_show`] =
        item[this.popupCtr.showKey];
      this.popupCtr.formName = "";
      this.popupCtr.showKey = "";
      this.searchValue = "";
      this.searchArray = [];
      this.popupVisible = false;
    },
    fuzzyInput(value) {//模糊搜索输入
      console.log("value", value);
      if (value == "") {
        this.searchArray = [];
      } else {
        const options = {
          includeScore: true,
          // Search in `author` and in `tags` array
          keys: [this.popupCtr.showKey]
        };
        const fuse = new Fuse(
          this[`${this.popupCtr.formName}ArrOrigin`],
          options
        );
        const result = fuse.search(value);
        this.searchArray = [];
        result.forEach(e => {
          this.searchArray.push(e.item);
        });
      }
    },
    fuzzyClear() {
      console.log("clear");
      this.form[this.popupCtr.formName] = "";
      this.showForm[`${this.popupCtr.formName}_show`] = "";
    },
    fuzzyAdd() {//模糊搜索点添加
      if (this.searchValue) {
        this.form[this.popupCtr.formName] = this.searchValue;
        this.showForm[`${this.popupCtr.formName}_show`] = this.searchValue;
        this.popupVisible = false;
      }
    },
    tenderDateConfirm(date) {
      console.log(date);
      this.form.tenderDate = formatDate(date, "yyyy-MM-dd");
      this.tenderDateShow = false;
    },
    canEditBtnClick() {
      if (this.canEdit) {
        // 取消 还原数据
        this.form = {
          reportPeople: "",
          cusFullName: "",
          projectName: "",
          mainPerson: "",
          mainPerPhone: "",
          position: "",
          engineerAgent: "",
          salesmanId: "",
          tenderDate: "",
          tenderRequest: "",
          brandQuantity: "",
          groupType: "",
          groupAreaDesc: "",
          detailFollowUp:''
        };
        let detail = this.$store.state.projectPurchase.projectPurchaseDetail;
        if (this.pageType == 1) {
          for (const key in detail) {
            if (detail.hasOwnProperty(key)) {
              const element = detail[key];
              this.form[key] = "" + element;
            }
          }
        }
        let salesmanArr = this.salesmanIdArrOrigin;
        for (let i = 0, len = salesmanArr.length; i < len; i++) {
          if (salesmanArr[i].id == detail.salesmanId) {
            this.showForm.salesmanId_show = salesmanArr[i].nickName;
            break;
          }
        }
        let cusArr = this.cusFullNameArrOrigin;
        this.showForm.cusFullName_show = detail.cusFullName;
        this.form.cusFullName = detail.groupCusAddDocumentId;
        for (let i = 0, len = cusArr.length; i < len; i++) {
          if (cusArr[i].id == detail.cusFullName) {
            this.showForm.cusFullName_show = cusArr[i].cusFullName;
            break;
          }
        }

        this.$nextTick(() => {
          let date = new Date(detail.tenderDate);
          this.tenderDateDefaultDate = date;
          this.$refs.calendar.reset();

          this.form.tenderDate = formatDate(date, "yyyy-MM-dd");
        });
      }
      this.canEdit = !this.canEdit;
    },
    okBtnClick() {
      this.$refs.form.submit();
    },
    formSubmited() {
      if (this.pageType == 0) {
        this.addProjectPurchase(this.form)
          .then(res => {
            console.log(res);
            if (res.success) {
              Toast.success("新建成功");
              this.$router.go(-1);
            } else {
              Toast.fail(`新建失败：${res.message}`);
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        this.updateProjectPurchase(this.form)
          .then(res => {
            console.log(res);
            if (res.success) {
              Toast.success("更新成功");
              // this.$router.go(-1);
            } else {
              Toast.fail(`更新失败：${res.message}`);
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.project-purchase-detail {
  .van-radio {
    margin-bottom: 8px;
  }
  .salesmanPopupContainer {
    max-height: 100vh;
    overflow: hidden;
    .salesmanItemContainer {
      overflow: auto;
      position: relative;
      max-height: 600px;
      .salesmanItem {
        padding: 8px 12px;
      }
    }
  }
  .bottomBtnCol {
    flex: 1;
    padding: 8px;
  }
}
</style>